const storeService = require('../services/storeService');
const { StatusCodes } = require('http-status-codes');
const Joi = require('joi');

// 验证规则
const storeSchema = Joi.object({
  name: Joi.string().required().min(2).max(100),
  address: Joi.string().required().min(5).max(255),
  phone: Joi.string().required().pattern(/^[0-9]{10,20}$/),
  manager_id: Joi.number().integer().allow(null),
  status: Joi.string().valid('active', 'inactive').default('active')
});

// 状态更新验证规则
const statusSchema = Joi.object({
  status: Joi.string().required().valid('active', 'inactive')
});

class StoreController {
  async createStore(req, res, next) {
    try {
      const { error, value } = storeSchema.validate(req.body);
      if (error) {
        return res.status(StatusCodes.BAD_REQUEST).json({
          error: error.details[0].message
        });
      }

      const store = await storeService.createStore(value);
      res.status(StatusCodes.CREATED).json(store);
    } catch (err) {
      next(err);
    }
  }

  async getStore(req, res, next) {
    try {
      const store = await storeService.getStoreById(req.params.id);
      res.status(StatusCodes.OK).json(store);
    } catch (err) {
      next(err);
    }
  }

  async getAllStores(req, res, next) {
    try {
      const { status } = req.query;
      const stores = await storeService.getAllStores({ status });
      res.status(StatusCodes.OK).json(stores);
    } catch (err) {
      next(err);
    }
  }

  async updateStore(req, res, next) {
    try {
      const { error, value } = storeSchema.validate(req.body);
      if (error) {
        return res.status(StatusCodes.BAD_REQUEST).json({
          error: error.details[0].message
        });
      }

      const store = await storeService.updateStore(req.params.id, value);
      res.status(StatusCodes.OK).json(store);
    } catch (err) {
      next(err);
    }
  }

  async updateStoreStatus(req, res, next) {
    try {
      console.log('更新门店状态请求:', req.body);
      const { error, value } = statusSchema.validate(req.body);
      if (error) {
        console.error('状态验证错误:', error.details);
        return res.status(StatusCodes.BAD_REQUEST).json({
          error: error.details[0].message
        });
      }

      const store = await storeService.updateStoreStatus(req.params.id, value.status);
      res.status(StatusCodes.OK).json(store);
    } catch (err) {
      console.error('更新门店状态错误:', err);
      next(err);
    }
  }

  async deleteStore(req, res, next) {
    try {
      await storeService.deleteStore(req.params.id);
      res.status(StatusCodes.NO_CONTENT).send();
    } catch (err) {
      next(err);
    }
  }
}

module.exports = new StoreController(); 